import gosu.Song;

import org.jruby.*;
import org.jruby.runtime.*;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.anno.JRubyMethod;
import static org.jruby.RubyNumeric.*;


public class SongProxy extends RubyObject {
  private static ObjectAllocator ALLOCATOR = new ObjectAllocator() {
    public IRubyObject allocate(Ruby runtime, RubyClass klass) {
      return new SongProxy(runtime, klass);
    }
  };

  private Song _song;

  private final Ruby _runtime;

  public static void createSongClass(Ruby runtime) {
    RubyModule mGosu = runtime.getModule("Gosu");
    RubyClass cSong = mGosu.defineClassUnder("Song", runtime.getObject(), ALLOCATOR);

    cSong.defineAnnotatedMethods(SongProxy.class);
  }


  public SongProxy(Ruby runtime, RubyClass type) {
    super(runtime, type);
    _runtime = runtime;
  }


  public Song getSong() { return _song; }


  @JRubyMethod(name = "initialize",
               required = 2,
               visibility = Visibility.PRIVATE)
  public IRubyObject initialize(IRubyObject window, IRubyObject filename) {
    _song = new Song(((WindowProxy) window).getWindow(), ((RubyString) filename).toString());
    return this;
  }


  @JRubyMethod(name = "play")
  public IRubyObject play() {
    _song.play();
    return _runtime.getNil();
  }


  @JRubyMethod(name = "stop")
  public IRubyObject stop() {
    _song.stop();
    return _runtime.getNil();
  }


  @JRubyMethod(name = "playing?")
  public IRubyObject isPlaying() {
    return _runtime.newBoolean(_song.isPlaying());
  }


  @JRubyMethod(name = "volume")
  public IRubyObject volume() {
    return _runtime.newFloat(_song.getVolume());
  }


  @JRubyMethod(name = "volume=",
               required = 1)
  public IRubyObject setVolume(IRubyObject vol) {
    _song.setVolume((float) num2dbl(vol));
    return _runtime.getNil();
  }
}
